package cn.ixinjiu.libraryMangement.controller.systemAdmin.admin;

import cn.ixinjiu.libraryMangement.entity.UserInfo;
import cn.ixinjiu.libraryMangement.service.IUserInfoService;
import cn.ixinjiu.libraryMangement.service.impl.UserInfoServiceImpl;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * Created by XinChen on 2023-06-11
 *
 * @TODO 修改用户信息
 */
@WebServlet("/userInfoUpd")
public class UserInfoUpdServlet extends HttpServlet {
    private IUserInfoService userInfoService = new UserInfoServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码格式
        req.setCharacterEncoding("utf-8");
        resp.setHeader("Content-Type", "text/html;charset=utf-8");

        // 获取前端参数
        int id = Integer.valueOf((req.getParameter("id")));
        String userName = req.getParameter("user_name");
        String password = req.getParameter("password");
        String avatar = (String) req.getSession().getAttribute("avatar");
        String email = req.getParameter("email");
        String phoneNumber = req.getParameter("phone_number");
        int role = Integer.valueOf(req.getParameter("role"));
        UserInfo userInfo = new UserInfo(id, userName, password, avatar, email, phoneNumber, role);

        // 修改用户信息
        int result = userInfoService.userInfoUpd(userInfo);

        // 信息修改之后，变更session中的值
        try {
            UserInfo userInfoById = userInfoService.getUserInfoById(id);
            req.getSession().setAttribute("userInfo", userInfoById);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        // 返回数据
        JSONObject json = new JSONObject();
        if (result == 1) {
            json.put("code", "0");
            json.put("msg", "修改成功");
        } else {
            json.put("code", "1");
            json.put("msg", "修改失败");
        }
        // 输出到页面
        PrintWriter writer = resp.getWriter();
        writer.write(json.toString());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
